package org.clevernote.foundations;

import com.evernote.edam.type.*;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.notestore.*;
import com.facebook.thrift.TException;

import java.util.List;

import org.clevernote.main.CmdListNotebooks;
import org.clevernote.main.CmdRunner;

public class EvernoteExtension {
	protected static final int BATCH_SIZE = 100;

	public static final String getNotebookGuid(String notebookName,
			NoteStore.Client noteStore, String authToken)
			throws EDAMUserException, EDAMSystemException, TException {
		List<Notebook> notebooks = (List<Notebook>) noteStore
				.listNotebooks(authToken);

		for (Notebook notebook : notebooks) {
			if (notebook.getName().equals(notebookName)) {
				return notebook.getGuid();
			}
		}

		return null;
	}

	public static final String StringToNoteContent(String noteText) {
		String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				+ "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml.dtd\">"
				+ "<en-note>" + noteText + "</en-note>";
		return content;
	}

	public static interface NoteVisitor {
		public void visitNote(Note note);
	}

	public static final int findNotes(NoteStore.Client noteStore,
			String authToken, NoteFilter filter, NoteVisitor visitor)
			throws EDAMUserException, EDAMSystemException, TException {
		int nvisited = 0;
		int offset = 0;
		int numNotes = 0;

		do {
			NoteList noteList = noteStore.findNotes(authToken, filter, offset,
					BATCH_SIZE);
			List<Note> notes = (List<Note>) noteList.getNotes();
			numNotes = notes.size();
			for (Note note : notes) {
				visitor.visitNote(note);
			}
			offset = offset + BATCH_SIZE;
			nvisited += numNotes;
		} while (numNotes >= BATCH_SIZE);

		return nvisited;
	}

}
